package controller;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.http.*;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import service.Utils;

@SuppressWarnings("serial")
public class NetworkToolServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		resp.setContentType("text/plain");
		resp.getWriter().println("Hello, world");
		resp.setHeader( "Cache-Control", "public, max-age=86400");
		resp.setHeader( "Expires", new Date(Calendar.getInstance().getTime().getTime()+24*60*60*1000).toGMTString());
		String name = req.getParameter("url");
		String type = req.getParameter("type");
		String result = "";
		if(name!=null&&type!=null)
		{
			try {
				URL dataURL = new URL("http://network-tools.com/default.asp?prog="+type+"&host="+name);

				BufferedReader reader = new BufferedReader(new InputStreamReader(
						dataURL.openStream(), Charset.forName("UTF-8")));
				String content = "";
				char[] buf = new char[102102];
				int numRead=0;
		        while((numRead=reader.read(buf)) != -1){
		            String readData = String.valueOf(buf, 0, numRead);
		            content += readData;
		            buf = new char[102102];
		        }
		        reader.close();

				Document doc = Jsoup.parse(content);
				doc.select("center").remove();
				result = doc.select("div[style=width:680px; float:left; margin-top:25px;]").get(0).html();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		req.setAttribute("result", Utils.cleanContent(result));
		req.setAttribute("name", name);
		req.setAttribute("type", type);
		try {
			req.getRequestDispatcher("/networktool.jsp").forward(req, resp);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}
